package com.lkd.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.PartnerDto;
import com.lkd.entity.Partner;
import com.lkd.mapper.PartnerMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.result.PageBean;
import com.lkd.service.PartnerService;
import com.lkd.vo.PartnerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    @Autowired
    private VendingMachineMapper vendingMachineMapper;
    @Override
    public Partner getById(Long id) {
        return partnerMapper.getById(id);
    }

    @Override
    public boolean create(Partner partner) {
        partner.setPassword("123");
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());
        return partnerMapper.create(partner);
    }

    @Override
    public boolean update(Partner partner) {
        partner.setUpdateTime(LocalDateTime.now());
        return partnerMapper.update(partner);
    }

    @Override
    public boolean delete(Long id) {
        return partnerMapper.delete(id);
    }

    //根据给定的条件分页查询合作伙伴信息，并返回包含分页信息的结果集。
    @Override
    public PageBean<PartnerVo> findByPage(PartnerDto dto) {
        if (dto.getPageIndex() == null || dto.getPageIndex() < 1){
            dto.setPageIndex(1);
        }
        if (dto.getPageSize() == null || dto.getPageSize() < 1){
            dto.setPageSize(10);
        }
        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());

        //查询符合条件的合作伙伴列表
        List<PartnerVo> list = partnerMapper.findList(dto);
        //将查询结果强转为Page类型，以便获取分页信息
        Page<PartnerVo> page = (Page<PartnerVo>) list;

        //遍历查询结果列表，针对每个合作伙伴查询其关联的自动售货机数量，并设置到合作伙伴实体中
        if (CollectionUtil.isNotEmpty(list)){
            for (PartnerVo partnerVo : list) {
                Integer count = vendingMachineMapper.countByPartnerId(partnerVo.getId());
                partnerVo.setVmCount(count);
            }
        }

        //创建PageBean对象，将分页信息和查询结果设置到PageBean中并返回
        PageBean<PartnerVo> pageBean = new PageBean<>();
        pageBean.setPageIndex(page.getPageNum());
        pageBean.setPageSize(page.getPageSize());
        pageBean.setTotalPage((long)page.getPages());
        pageBean.setTotalCount(page.getTotal());
        pageBean.setCurrentPageRecords(page.getResult());
        return pageBean;
    }
}
